Imports System.IO
Imports System.Xml

Module Library_Files

    ' Return the file's contents in a string.
    Public Function GetFileContents(ByVal file_name As String) As String
        Dim stream_reader As New StreamReader(file_name)
        Dim text As String = stream_reader.ReadToEnd()

        stream_reader.Close()
        Return text
    End Function

    ' Write a file from a string.
    Public Sub SetFileContents(ByVal file_name As String, ByVal file_contents As String)
        Dim stream_writer As New StreamWriter(file_name)

        stream_writer.Write(file_contents)
        stream_writer.Close()
    End Sub

    ' Return the location of the Data subdirectory
    ' without a trailing \.
    Public Function DataSubdirectory() As String
        Dim startup_path As String
        Dim data_path As String
        Dim pos As Integer

        ' Remove the trailing \ if any. Normally 
        ' StartupPath returns "C:\" but "C:\Test".
        startup_path = Application.StartupPath
        If startup_path.EndsWith("\") Then startup_path = startup_path.Remove(startup_path.Length - 1, 1)

        ' Look in the startup directory.
        data_path = startup_path & "\Data"
        If Directory.Exists(data_path) Then
            ' Return the startup directory's Data subdirectory.
            Return data_path
        End If

        ' There is no Data directory here.
        ' Look up one level.
        pos = startup_path.LastIndexOf("\")
        If pos = 0 Then
            ' There is no parent directory (e.g. we're at C:).
            ' Return the startup path.
            Return startup_path
        End If

        ' Look for the Data directory in the parent directory.
        data_path = startup_path.Substring(0, pos) & "\Data"
        If Directory.Exists(data_path) Then
            ' The parent has a Data directory.
            ' Return it.
            Return data_path
        End If

        ' Our parent directory doesn't have a
        ' Data subdirectory. Return the startup path.
        Return startup_path
    End Function

    ' Return the file's name without its path.
    Public Function FileTitle(ByVal file_name As String) As String
        Dim pos As Integer

        pos = InStrRev(file_name, "\")
        If pos = 0 Then pos = InStrRev(file_name, ":")
        If pos = 0 Then
            Return file_name
        Else
            Return file_name.Substring(pos)
        End If
    End Function
End Module
